package com.cljz.makepassenger.ui.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cljz.makepassenger.R;
import com.cljz.makepassenger.base.App;
import com.cljz.makepassenger.base.BaseActivity;
import com.cljz.makepassenger.event.EMMessageEvent;
import com.cljz.makepassenger.event.RefreshEvent;
import com.cljz.makepassenger.event.UserInfoChangeEvent;
import com.cljz.makepassenger.model.net.bean.ActivityIndexBean;
import com.cljz.makepassenger.model.net.bean.AdListBean;
import com.cljz.makepassenger.model.net.bean.GetUserInfoBean;
import com.cljz.makepassenger.model.net.bean.InviteListBean;
import com.cljz.makepassenger.model.net.bean.NoticeListBean;
import com.cljz.makepassenger.present.activity.MainP;
import com.cljz.makepassenger.ui.ItemDecoration.SpacesItemDecoration;
import com.cljz.makepassenger.ui.adapter.DrawMenuAdapter;
import com.cljz.makepassenger.ui.adapter.HotEventsAdapter;
import com.cljz.makepassenger.ui.adapter.InviteListAdapter;
import com.cljz.makepassenger.ui.fragment.MainMenuFragment;
import com.cljz.makepassenger.ui.fragment.SettingMenuFragment;
import com.cljz.makepassenger.ui.helper.OnStartDragListener;
import com.cljz.makepassenger.utils.CommonUtils;
import com.cljz.makepassenger.utils.L;
import com.cljz.makepassenger.utils.T;
import com.cljz.makepassenger.widget.LetterDialogView;
import com.cljz.makepassenger.widget.NoScrollViewPager;
import com.clzj.makepassenger.bean.UserInfo;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.controller.EaseUI;
import com.jakewharton.rxbinding.view.RxView;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ObjectAnimator;
import com.squareup.picasso.Picasso;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.event.BusProvider;
import cn.droidlover.xdroidmvp.kit.Codec;
import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.router.Router;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import de.hdodenhof.circleimageview.CircleImageView;
import rx.functions.Action1;

import static com.cljz.makepassenger.R.id.iv_head;


/**
 * Created by apple on 2017/4/5.
 */

public class MainActivity extends BaseActivity<MainP> implements OnStartDragListener, HotEventsAdapter.OnItemClickListener, DrawerLayout.DrawerListener {

    @BindView(R.id.iv_notice)
    ImageView ivNotice;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.iv_home_list)
    ImageView ivHomeList;
    @BindView(iv_head)
    CircleImageView ivHead;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.iv_edit)
    ImageView ivEdit;
    @BindView(R.id.tv_age)
    TextView tvAge;
    @BindView(R.id.iv_age_icon)
    ImageView ivAgeIcon;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.vp_menu)
    public NoScrollViewPager nvpMenu;
    @BindView(R.id.ll_mine)
    LinearLayout llMine;
    @BindView(R.id.xrv_invite)
    XRecyclerView xrvInvite;
    @BindView(R.id.civ_portrait)
    CircleImageView civPortrait;
    @BindView(R.id.iv_main_button)
    ImageView ivMainButton;
    @BindView(R.id.fl_contain)
    FrameLayout flContain;
    @BindView(R.id.fl_home_list)
    FrameLayout flHomeList;
    @BindView(R.id.fl_notice)
    FrameLayout flNotice;

    /**
     * 头布局
     */
    private View xrvInviteHeader;
    SliderLayout slBanner;
    LinearLayout llBanner;
    LinearLayout guideCardView;
    TextView tvGuideTitle;
    RelativeLayout rlGuideDelete;
    TextView tvGuideDetails;
    TextView tvGuideTime;
    TextView tvLetterTitle;
    RelativeLayout rlLetterDelete;
    TextView tvLetterDetails;
    TextView tvLetterTime;
    LinearLayout letterCardView;
    RelativeLayout rlNoMsg;
    private LinearLayout llHot;
    private ImageButton ibMoreHot;
    private RecyclerView rvHotEvents;
    ImageView ivAd;


    private List<InviteListBean.DataBean> invitations = new ArrayList<>();
    private InviteListAdapter inviteListAdapter;
    private boolean isRefresh;
    private int page = 1;
    private boolean isLoadMore;
    private LetterDialogView letterDialogView;
    private Vibrator myVibrator;
    final Handler vibratorHandler = new VibratorHandler(this);
    private static final int VIBRATOR = 10;
    private PopupWindow menuPopupWindow;
    private List<ImageView> buttonList = new ArrayList<>();
    private int ButtonFlag = 1;

    StringBuilder dialogGuideText = new StringBuilder();
    StringBuilder dialogLetterText = new StringBuilder();
    StringBuilder dialogLetterSign = new StringBuilder();

    final Handler jPushHandler = new JPushHandler(this);
    private String warnId;
    private List<ActivityIndexBean.DataBean.ActivityBean> hotEventsList;
    private HotEventsAdapter hotEventsAdapter;

    private ArrayList<NoticeListBean.DataBeanX> noticeList;

    private long mExitTime;
    //    private GroupListActivity groupListActivity;
    private boolean showDrawer = false;
    private ActivityIndexBean.DataBean.AdBean adBean;

    public XRecyclerView getXrvInvite() {
        return xrvInvite;
    }

    public void setIvNotice() {
        ivNotice.setImageResource(R.mipmap.home_message_r);
    }

    @Override

    public void initData(Bundle savedInstanceState) {
        initPermission();
        //初始化头像
        Picasso.with(this).load(getP().getLocalUserInfo(getP().getToken()).getUser_logo()).error(R.mipmap.head_loading).placeholder(R.mipmap.head_loading).into(civPortrait);
        initHead();
        initDrawMenu();
        initRecycleView();
        setEM();
        setJPush();


    }

    private void setEM() {
        String emId = getP().getLocalUserInfo(getP().getToken()).getEid();
//        groupListActivity = (GroupListActivity) ActivityManager.getInstance().findActivity(GroupListActivity.class);
        EMClient.getInstance().login(emId, emId, new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                //此方法传入一个字符串String类型的参数，返回成功或失败的一个Boolean类型的返回值
                EMClient.getInstance().updateCurrentUserNick(getP().getLocalUserInfo(getP().getToken()).getUser_nickname());
                EMClient.getInstance().chatManager().addMessageListener(messageListener);
                Log.e("main", "登录聊天服务器成功！");
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                Log.d("main", "登录聊天服务器失败！");
            }
        });


    }

    private void initDrawMenu() {
        //初始化左菜单
        ArrayList<Fragment> menuFragments = new ArrayList<>();
        menuFragments.add(MainMenuFragment.newInstance());
        menuFragments.add(SettingMenuFragment.newInstance());
        nvpMenu.setAdapter(new DrawMenuAdapter(getSupportFragmentManager(), menuFragments));
        nvpMenu.setCurrentItem(0);
        updateDrawMenuData();

    }

    /**
     * 加载头布局
     */
    private void initHead() {
        xrvInviteHeader = LayoutInflater.from(this).inflate(R.layout.item_header, null);
        llBanner = (LinearLayout) xrvInviteHeader.findViewById(R.id.ll_banner);
        slBanner = (SliderLayout) xrvInviteHeader.findViewById(R.id.sl_banner);
        guideCardView = (LinearLayout) xrvInviteHeader.findViewById(R.id.guide_card_view);
        tvGuideTitle = (TextView) xrvInviteHeader.findViewById(R.id.tv_guide_title);
        rlGuideDelete = (RelativeLayout) xrvInviteHeader.findViewById(R.id.rl_guide_delete);
        tvGuideDetails = (TextView) xrvInviteHeader.findViewById(R.id.tv_guide_details);
        tvGuideTime = (TextView) xrvInviteHeader.findViewById(R.id.tv_guide_time);
        tvLetterTitle = (TextView) xrvInviteHeader.findViewById(R.id.tv_letter_title);
        rlLetterDelete = (RelativeLayout) xrvInviteHeader.findViewById(R.id.rl_letter_delete);
        tvLetterDetails = (TextView) xrvInviteHeader.findViewById(R.id.tv_letter_details);
        tvLetterTime = (TextView) xrvInviteHeader.findViewById(R.id.tv_letter_time);
        letterCardView = (LinearLayout) xrvInviteHeader.findViewById(R.id.letter_card_view);
        rlNoMsg = (RelativeLayout) xrvInviteHeader.findViewById(R.id.rl_no_msg);
        llHot = (LinearLayout) xrvInviteHeader.findViewById(R.id.ll_hot);
        ibMoreHot = (ImageButton) xrvInviteHeader.findViewById(R.id.ib_more_hot);
        rvHotEvents = (RecyclerView) xrvInviteHeader.findViewById(R.id.rv_hot_events);
        ivAd = (ImageView) xrvInviteHeader.findViewById(R.id.iv_ad);
//        ivAd.setPadding(0,20,0,0);
        int screenWidth = CommonUtils.getScreenWidth(this);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) ivAd.getLayoutParams();
        lp.width = screenWidth;
        lp.height = screenWidth * 120 / 750;
        L.e("width:" + lp.width + "::height" + lp.height);
        lp.setMargins(0, 20, 0, 0);
        ivAd.setLayoutParams(lp);
//        ivAd.setScaleType(ImageView.ScaleType.FIT_XY);
        ivAd.setMaxWidth(screenWidth);
        ivAd.setMaxHeight(screenWidth);

        //初始化banner
        slBanner.setFocusable(true);
        slBanner.setFocusableInTouchMode(true);
        slBanner.requestFocus();

        //初始化热门活动
        RxView.clicks(ibMoreHot)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.newIntent((Activity) App.getInstance())
                                .to(NearbyActivity.class)
                                .launch();
                    }
                });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvHotEvents.setLayoutManager(linearLayoutManager);
        hotEventsAdapter = new HotEventsAdapter(this, hotEventsList);
        rvHotEvents.setAdapter(hotEventsAdapter);
        rvHotEvents.addItemDecoration(new SpacesItemDecoration(Kits.Dimens.dpToPxInt(this, 5)));
        ivAd.setVisibility(View.GONE);
        getP().getBanner();
//        getP().getLetter();
        getP().getActivityIndex();

    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle extras = intent.getExtras();
        showDrawer = extras.getBoolean("showDrawer");
    }

    @Override
    protected void onResume() {
        super.onResume();
        getP().getNoticeList(1);
        if (showDrawer) {
            drawerLayout.openDrawer(GravityCompat.START);
            showDrawer = false;
        }

        Picasso.with(this).load(getP().getLocalUserInfo(getP().getToken()).getUser_logo()).error(R.mipmap.head_loading).placeholder(R.mipmap.head_loading).into(civPortrait);
    }

    private void initRecycleView() {
        xrvInvite.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        inviteListAdapter = new InviteListAdapter(this, invitations);
        xrvInvite.setAdapter(inviteListAdapter);
        xrvInvite.setLoadingMoreProgressStyle(ProgressStyle.BallClipRotate);
        xrvInvite.setPullRefreshEnabled(true);
        xrvInvite.setLoadingMoreEnabled(true);
        xrvInvite.addHeaderView(xrvInviteHeader);
        xrvInvite.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                Log.e("refreshAndLoadMore", "onRefresh");
                page = 1;
                getP().getBanner();
                getP().getActivityIndex();
                getP().getInviteList(page);
            }

            @Override
            public void onLoadMore() {
                isLoadMore = true;
                Log.e("refreshAndLoadMore", "onLoadMore");
                page++;
                getP().getInviteList(page);
            }
        });
        xrvInvite.refresh();
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }


    @Override
    public MainP newP() {
        return new MainP();
    }

    @Override
    protected void initListener() {
        super.initListener();
        drawerLayout.setDrawerListener(this);
        RxView.clicks(flHomeList)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        toggle();
                    }
                });
        RxView.longClicks(ivMainButton)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.newIntent((Activity) App.getInstance())
                                .to(NearbyActivity.class)
                                .launch();
                    }
                });
        RxView.clicks(ivMainButton)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.newIntent((Activity) App.getInstance()).to(EditorInvitedActivity.class).putInt("type", EditorInvitedActivity.EDITOR_INVITE).launch();
                    }
                });
        RxView.clicks(rlGuideDelete)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        getP().getMsgDel("2");
                        guideCardView.setVisibility(View.GONE);
                    }
                });
        RxView.clicks(rlLetterDelete)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        getP().getMsgDel("1");
                        letterCardView.setVisibility(View.GONE);
                    }
                });
        RxView.clicks(letterCardView)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        showLetter("1Q聚会玩给你的一封信！", dialogLetterText.toString(), dialogLetterSign.toString());
                    }
                });
        RxView.clicks(guideCardView)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        showLetter("1Q操作说明！", dialogGuideText.toString(), "");
                    }
                });

        RxView.clicks(ivAd)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        // TODO: 2017/6/14
                        if ("1".equals(adBean.getLink_type())) {
                            String link = adBean.getAd_link();
                            Uri uri = Uri.parse(link);
                            String path = uri.getLastPathSegment();
                            String activityID = uri.getQueryParameter("id"); //解析参数
                            if ("activityDetail".equals(path) && activityID != null) {
                                int type = InvitationLetterActivity.INVITE;
                                Router.newIntent((Activity) App.getInstance()).putString("id", activityID).putInt("type", type).to(InvitationLetterActivity.class).launch();
                            }
                        } else if ("2".equals(adBean.getLink_type())) {
                            // TODO: 2017/4/25 1 webview
                            Router.newIntent((Activity) App.getInstance())
                                    .to(WapActivity.class)
                                    .launch();
                        }
                    }
                });
        RxView.clicks(ivNotice)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        ivNotice.setImageResource(R.mipmap.home_message);
                        Router.newIntent((Activity) App.getInstance())
                                .putSerializable("noticeList", noticeList)
                                .to(GroupListActivity.class)
                                .launch();

                    }
                });
        RxView.clicks(llMine)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.newIntent((Activity) App.getInstance())
                                .to(IDSettingActivity.class)
                                .launch();
                    }
                });
        hotEventsAdapter.setOnItemClickListener(this);
    }


    @Override
    protected void onStop() {
        if (menuPopupWindow != null && menuPopupWindow.isShowing()) {
            buttonDismissAnimation(buttonList);
        }
        if (slBanner != null) {
            slBanner.stopAutoCycle();
        }
        drawerLayout.closeDrawer(GravityCompat.START);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        vibratorHandler.removeCallbacksAndMessages(null);
        if (slBanner != null) {
            slBanner.stopAutoCycle();
        }
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
        EMClient.getInstance().logout(true, new EMCallBack() {

            @Override
            public void onSuccess() {
                L.e("环信退出");
            }

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onError(int code, String message) {
            }
        });

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                T.getInstance().showShort("再按一次退出程序");
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showMenuPopWindow() {

        View view = View.inflate(this, R.layout.pop_show_menu, null);
        ImageView personButton = (ImageView) view.findViewById(R.id.ib_personal);
        ImageView settingButton = (ImageView) view.findViewById(R.id.ib_setting);
        ImageView chatButton = (ImageView) view.findViewById(R.id.ib_chat);
        ImageView dismissButton = (ImageView) view.findViewById(R.id.ib_dismiss);
        buttonList.add(personButton);
        buttonList.add(settingButton);
        buttonList.add(chatButton);
        RxView.clicks(dismissButton)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        buttonDismissAnimation(buttonList);
                    }
                });
        RxView.clicks(personButton)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.newIntent((Activity) App.getInstance()).to(MineActivity.class).launch();
                    }
                });
        RxView.clicks(settingButton)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.newIntent((Activity) App.getInstance()).to(SettingActivity.class).launch();
                    }
                });
        RxView.clicks(chatButton)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.newIntent((Activity) App.getInstance()).to(FeedbackActivity.class).launch();

                    }
                });

        menuPopupWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, false);
        menuPopupWindow.setTouchable(true);
        menuPopupWindow.setOutsideTouchable(false);
        menuPopupWindow.update();
        menuPopupWindow.showAtLocation(flContain, Gravity.CENTER, 0, 0);
        buttonShowAnimation(buttonList, Kits.Dimens.dpToPxInt(this, 120));
    }

    public void buttonShowAnimation(List<ImageView> buttonList, int radius) {

        for (int i = 0; i < buttonList.size(); i++) {

            ObjectAnimator objAnimatorX;
            ObjectAnimator objAnimatorY;
            ObjectAnimator objAnimatorRotate;

            // 按钮在X、Y方向的移动距离
            float distanceX = (float) (ButtonFlag * radius * (Math.cos(getAngle(buttonList.size(), i))));
            float distanceY = -(float) (radius);


            // X方向移动
            objAnimatorX = ObjectAnimator.ofFloat(buttonList.get(i), "x", ivMainButton.getX(), ivMainButton.getX() + distanceX);
            objAnimatorX.setDuration(200);
            objAnimatorX.setStartDelay(100);
            objAnimatorX.start();

            // Y方向移动
            objAnimatorY = ObjectAnimator.ofFloat(buttonList.get(i), "y", ivMainButton.getY(), ivMainButton.getY() + distanceY);
            objAnimatorY.setDuration(200);
            objAnimatorY.setStartDelay(100);
            objAnimatorY.start();

            // 按钮旋转
            objAnimatorRotate = ObjectAnimator.ofFloat(buttonList.get(i), "rotation", 0, 360);
            objAnimatorRotate.setDuration(200);
            objAnimatorRotate.setStartDelay(100);
            objAnimatorRotate.start();
        }
        ivMainButton.setImageDrawable(getResources().getDrawable(R.mipmap.close));
        ButtonFlag = -1;
    }

    private void buttonDismissAnimation(final List<ImageView> buttonList) {
        for (int i = 0; i < buttonList.size(); i++) {

            ObjectAnimator objAnimatorX;
            ObjectAnimator objAnimatorY;
            ObjectAnimator objAnimatorRotate;
            // X方向移动
            objAnimatorX = ObjectAnimator.ofFloat(buttonList.get(i), "x", buttonList.get(i).getX(), ivMainButton.getX());
            objAnimatorX.setDuration(200);
            objAnimatorX.setStartDelay(100);
            objAnimatorX.start();

            // Y方向移动
            objAnimatorY = ObjectAnimator.ofFloat(buttonList.get(i), "y", buttonList.get(i).getY(), ivMainButton.getY());
            objAnimatorY.setDuration(200);
            objAnimatorY.setStartDelay(100);
            objAnimatorY.start();

            // 按钮旋转
            objAnimatorRotate = ObjectAnimator.ofFloat(buttonList.get(i), "rotation", 360, 0);
            objAnimatorRotate.setDuration(200);
            objAnimatorRotate.setStartDelay(100);
            objAnimatorRotate.start();
            objAnimatorX.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    if (menuPopupWindow != null && menuPopupWindow.isShowing()) {
                        menuPopupWindow.dismiss();
                        menuPopupWindow = null;
                    }
                    buttonList.clear();
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
        }
        ivMainButton.setImageDrawable(getResources().getDrawable(R.mipmap.button_r));
        ButtonFlag = 1;
    }

    public double getAngle(int total, int index) {
        return Math.toRadians(135 - 90 / (total - 1) * index);
    }

    public void msgDelSucceed() {
//        getP().getLetter();
    }

    public void msgDelFail(String error) {
//        getP().getLetter();

    }


    public void getNoticeListSucceed(ArrayList<NoticeListBean.DataBeanX> data) {
        if (data.size() > 0) {
            if (noticeList != null) {
                if (!data.get(0).getExtra().getData().getInvite_id().equals(noticeList.get(0).getExtra().getData().getInvite_id())) {
                    ivNotice.setImageResource(R.mipmap.home_message_r);
                }
            } else {
                ivNotice.setImageResource(R.mipmap.home_message_r);
            }
            noticeList = data;
        }

    }

    public void getNoticeListFail(String error) {

    }

    public void getActivityIndexSucceed(final ActivityIndexBean.DataBean data) {
        if (data == null || data.getActivity().size() == 0) {
            llHot.setVisibility(View.GONE);
        } else {
            llHot.setVisibility(View.VISIBLE);
            hotEventsList = data.getActivity();
            hotEventsAdapter.setData(hotEventsList);
        }
        if (data == null || data.getAd().size() == 0) {
            ivAd.setVisibility(View.GONE);
        } else {
            ivAd.setVisibility(View.VISIBLE);
            adBean = data.getAd().get(0);
            Picasso.with(App.getInstance())
                    .load(adBean.getAd_logo())
                    .into(ivAd);

        }

    }

    public void getActivityIndexFail(String error) {

    }

    @Override
    public void onClick(ActivityIndexBean.DataBean.ActivityBean dataBean) {
        Router.newIntent((Activity) App.getInstance())
                .to(InvitationLetterActivity.class)
                .putString("id", dataBean.getId())
                .putInt("type", InvitationLetterActivity.ACTIVITY)
                .launch();
    }

    @Override
    public void onLongClick(ActivityIndexBean.DataBean.ActivityBean dataBean) {

    }

    public void getUserInfoSucceed(GetUserInfoBean.DataBean dataBean) {
        updateDrawMenuData();
    }

    private void updateDrawMenuData() {
        UserInfo userInfo = getP().getLocalUserInfo(getP().getToken());
        Picasso.with(MainActivity.this).load(userInfo.getUser_logo()).error(R.mipmap.head_loading).placeholder(R.mipmap.head_loading).into(ivHead);
        String nickName = userInfo.getUser_nickname();
        if (nickName.length() > 6) {
            nickName = nickName.substring(0, 5) + "...";
        }
        tvNickname.setText(nickName);
        tvAge.setText(userInfo.getAge());
        Picasso.with(this).load("0".equals(userInfo.getUser_sex()) ? R.mipmap.secret : ("1".equals(userInfo.getUser_sex()) ? R.mipmap.icon_boy : R.mipmap.icon_girl)).into(ivAgeIcon);
    }

    public void getUserInfoFail(String error) {

    }

//    @Override
//    public void onMessageReceived(List<EMMessage> messages) {
//        // notify new message
//        for (EMMessage message : messages) {
//            EaseUI.getInstance().getNotifier().onNewMsg(message);
//        }
//        L.e("GroupListRefresh");
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//
//                BusProvider.getBus().post(new EMMessageEvent());
//                L.e("GroupListRefresh");
////                    if (groupListActivity != null) {
////                        groupListActivity.refresh();
////                    }
//
//                android.app.ActivityManager am = (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//                List<android.app.ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
//                if (list != null && list.size() > 0) {
//                    ComponentName cpn = list.get(0).topActivity;
//                    ivNotice.setImageResource(R.mipmap.home_message_r);
//                }
//
//            }
//        });
//    }
//
//    @Override
//    public void onCmdMessageReceived(List<EMMessage> list) {
//
//    }
//
//    @Override
//    public void onMessageRead(List<EMMessage> list) {
//
//    }
//
//    @Override
//    public void onMessageDelivered(List<EMMessage> list) {
//
//    }
//
//    @Override
//    public void onMessageChanged(EMMessage emMessage, Object o) {
//
//    }


    private static class VibratorHandler extends Handler {
        private final WeakReference<MainActivity> mActivity;

        private VibratorHandler(MainActivity activity) {
            mActivity = new WeakReference<MainActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = mActivity.get();
            switch (msg.what) {
                case VIBRATOR:
                    activity.myVibrator.cancel();
                    break;
            }
        }
    }

    public void showBanner(final List<AdListBean.DataBean> ad_logo) {
        slBanner.removeAllSliders();
        if (ad_logo.size() == 0) {
            llBanner.setVisibility(View.GONE);
            return;
        } else {
            llBanner.setVisibility(View.VISIBLE);
        }
        for (int i = 0; i < ad_logo.size(); i++) {
            TextSliderView tsv = new TextSliderView(this);
            if ("0".equals(ad_logo.get(i).getLink_type())) {
                tsv
                        .description("")
                        .image(ad_logo.get(i).getAd_logo())
                        .setScaleType(BaseSliderView.ScaleType.CenterCrop)
                        .setOnSliderClickListener(new BaseSliderView.OnSliderClickListener() {
                            @Override
                            public void onSliderClick(BaseSliderView slider) {
//                                Router.newIntent((Activity) App.getInstance())
//                                        .to(WapActivity.class)
//                                        .launch();
                            }
                        });
            } else {
                final int finalI = i;
                tsv.description("")
                        .image(ad_logo.get(i).getAd_logo())
                        .setScaleType(BaseSliderView.ScaleType.CenterCrop)
                        .setOnSliderClickListener(new BaseSliderView.OnSliderClickListener() {
                            @Override
                            public void onSliderClick(BaseSliderView slider) {
                                if ("1".equals(ad_logo.get(finalI).getLink_type())) {
                                    String link = ad_logo.get(finalI).getAd_link();
                                    Uri uri = Uri.parse(link);
                                    String path = uri.getLastPathSegment();
                                    String activityID = uri.getQueryParameter("id"); //解析参数
                                    if ("activityDetail".equals(path) && activityID != null) {
                                        int type = InvitationLetterActivity.INVITE;
                                        Router.newIntent((Activity) App.getInstance()).putString("id", activityID).putInt("type", type).to(InvitationLetterActivity.class).launch();
                                    }
                                } else if ("2".equals(ad_logo.get(finalI).getLink_type())) {
                                    // TODO: 2017/4/25 1 webview
                                    Router.newIntent((Activity) App.getInstance())
                                            .to(WapActivity.class)
                                            .launch();
                                }
                            }
                        });

            }
            slBanner.addSlider(tsv);
        }
        slBanner.setPresetTransformer(SliderLayout.Transformer.Default);
        slBanner.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
        slBanner.setCustomAnimation(null);
        slBanner.setDuration(3000);
        llBanner.setVisibility(View.VISIBLE);
    }

    public void showBannerErr(String err) {
        llBanner.setVisibility(View.GONE);
    }


    public void showLetter(InviteListBean.Data2Bean data) {
        if ("1".equals(data.getMsg().getGuide_del())) {
            int size = data.getGuide().size();
            dialogLetterText.setLength(0);
            dialogLetterSign.setLength(0);
            StringBuilder guideText = new StringBuilder();
            for (int i = 0; i < size; i++) {
                guideText.append(data.getGuide().get(i));
                dialogGuideText.append(data.getGuide().get(i));
                if (i != size - 1) {
                    dialogGuideText.append("\r\n");
                }
            }
            tvGuideDetails.setText(guideText);
//            StringBuilder guideTime = new StringBuilder();
//            guideTime.append(data.getDate()).append(" ").append(data.getWeek()).append(" ").append(Kits.Date.getHm(System.currentTimeMillis()));
            tvGuideTime.setText(Kits.Date.getMdhm(System.currentTimeMillis()));
            guideCardView.setVisibility(View.VISIBLE);
        } else {
            guideCardView.setVisibility(View.GONE);
        }
        if ("1".equals(data.getMsg().getLetter_del())) {
            int size = data.getLetter().size();
            dialogLetterText.setLength(0);
            StringBuilder letterText = new StringBuilder();
            for (int i = 0; i < size; i++) {
                letterText.append(data.getLetter().get(i));
                if (i != size - 1) {
                    dialogLetterText.append("    " + data.getLetter().get(i));
                    if (i != size - 2) {
                        dialogLetterText.append("\r\n");
                    }
                } else {
                    dialogLetterSign.append(data.getLetter().get(i));
                }
            }
            tvLetterDetails.setText(letterText);
//            StringBuilder letterTime = new StringBuilder();
//            letterTime.append(data.getDate()).append(" ").append(data.getWeek()).append(" ").append(Kits.Date.getHm(System.currentTimeMillis()));
            tvLetterTime.setText(Kits.Date.getMdhm(System.currentTimeMillis()));
            letterCardView.setVisibility(View.VISIBLE);
        } else {
            letterCardView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onStartDrag(RecyclerView.ViewHolder viewHolder) {

    }

    public void getInviterListFail(String error) {
//        dismissLoadingDialog();
        if (isLoadMore) {
            xrvInvite.loadMoreComplete();
            isLoadMore = false;
        } else {
            xrvInvite.refreshComplete();
            isRefresh = false;
        }
    }

    public void getInviterListSucceed(List<InviteListBean.DataBean> dataBeanList) {
        invitations = dataBeanList;
        if (isLoadMore) {
            xrvInvite.loadMoreComplete();
            if (dataBeanList.size() == 0) {
                xrvInvite.setNoMore(true);
            } else {
                xrvInvite.setNoMore(false);
                inviteListAdapter.addData(dataBeanList);
            }
//            invitations.addAll(dataBeanList);
            isLoadMore = false;
        } else if (isRefresh) {
            xrvInvite.refreshComplete();
            xrvInvite.setNoMore(false);
            if (dataBeanList.size() == 0) {
                rlNoMsg.setVisibility(View.VISIBLE);
            } else {
//                if (dataBeanList.size() < 10) {
//                    xrvInvite.setNoMore(true);c
//                }
                invitations = dataBeanList;
                inviteListAdapter.setData(invitations);
                rlNoMsg.setVisibility(View.GONE);
            }
            isRefresh = false;
        }
    }

    private void showLetter(String title, String text, String sign) {
        letterDialogView = new LetterDialogView(this, R.style.MyDialog, new LetterDialogView.YesDialogListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.iv_close:
                        letterDialogView.dismiss();
                        break;
                }
            }
        });
        letterDialogView.show();
        TextView tvLetterTitle = (TextView) letterDialogView.findViewById(R.id.tv_letter_title);
        TextView tvLetterText = (TextView) letterDialogView.findViewById(R.id.tv_letter_text);
        TextView tvLetterSign = (TextView) letterDialogView.findViewById(R.id.tv_letter_sign);
        tvLetterTitle.setText(title);
        tvLetterText.setText(text);
        tvLetterSign.setText(sign);
    }

    /**
     * 邀请提示
     */
    private void showInvitePopupWindow(View view) {
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.pop_new_invite, null);
        PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setTouchable(true);
//        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                return_1 false;
//            }
//        });
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAsDropDown(view);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (slBanner != null) {
            slBanner.startAutoCycle();
        }
    }

    @Override
    public void loginOvertime(int i) {
        if (isLoadMore) {
            xrvInvite.loadMoreComplete();
            isLoadMore = false;
        } else if (isRefresh) {
            xrvInvite.refreshComplete();
            isRefresh = false;
        }
        super.loginOvertime(i);
    }

    private static final int MSG_SET_ALIAS = 1234;

    private static class JPushHandler extends Handler {
        private final WeakReference<MainActivity> mActivity;

        JPushHandler(MainActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = mActivity.get();
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    JPushInterface.setAliasAndTags(App.instance, (String) msg.obj, null, activity.runPushTag());
                    break;
            }
        }
    }

    private class PushTag implements TagAliasCallback {
        @Override
        public void gotResult(int code, String alias, Set<String> set) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    // 延迟 60 秒来调用 Handler 设置别名
                    jPushHandler.sendMessageDelayed(jPushHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
            }
        }

    }

    //极光设置别名
    public void setJPush() {
        // 调用 Handler 来异步设置别名
        String alias = Codec.MD5.getMessageDigest(getP().getLocalUserInfo(getP().getToken()).getToken().getBytes());
        L.e("alias", alias);
        try {
            if (getP().getLocalUserInfo(getP().getToken()) != null)
                jPushHandler.sendMessage(jPushHandler.obtainMessage(MSG_SET_ALIAS, alias));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public TagAliasCallback runPushTag() {
        return new PushTag();
    }

    @Override
    public boolean useEventBus() {
        return true;
    }

    @Override
    public void bindEvent() {
        super.bindEvent();
        BusProvider.getBus().toObservable(RefreshEvent.class)
                .compose(this.<RefreshEvent>bindToLifecycle())
                .subscribe(new Action1<RefreshEvent>() {
                    @Override
                    public void call(RefreshEvent refreshEvent) {
                        L.e("RefreshEvent");
                        xrvInvite.refresh();
                    }
                });
        BusProvider.getBus().toObservable(UserInfoChangeEvent.class)
                .compose(this.<UserInfoChangeEvent>bindToLifecycle())
                .subscribe(new Action1<UserInfoChangeEvent>() {
                    @Override
                    public void call(UserInfoChangeEvent userInfoChangeEvent) {
                        getP().getUserInfo();


                    }
                });
    }

    /**
     * 自定义NavigationIcon设置关联DrawerLayout
     */
    private void toggle() {
        int drawerLockMode = drawerLayout.getDrawerLockMode(GravityCompat.START);
        if (drawerLayout.isDrawerVisible(GravityCompat.START)
                && (drawerLockMode != DrawerLayout.LOCK_MODE_LOCKED_OPEN)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else if (drawerLockMode != DrawerLayout.LOCK_MODE_LOCKED_CLOSED) {
            drawerLayout.openDrawer(GravityCompat.START);
        }
    }

    @Override
    public void onDrawerSlide(View drawerView, float slideOffset) {
        // 导航图标渐变效果
        ivHomeList.setAlpha(1 - slideOffset);
        // 判断是否左菜单并设置移动(如果不这样设置,则主页面的内容不会向右移动)
        if (drawerView.getTag().equals("left")) {
            View content = drawerLayout.getChildAt(0);
            int offset = (int) (drawerView.getWidth() * slideOffset);
            content.setTranslationX(offset);

        }
//        tintManager.setStatusBarAlpha(1 - slideOffset);
    }

    @Override
    public void onDrawerOpened(View drawerView) {

    }

    @Override
    public void onDrawerClosed(View drawerView) {

    }

    @Override
    public void onDrawerStateChanged(int newState) {
    }

    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // notify new message
            for (EMMessage message : messages) {
                EaseUI.getInstance().getNotifier().onNewMsg(message);
            }
            L.e("GroupListRefresh");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    BusProvider.getBus().post(new EMMessageEvent());
                    L.e("GroupListRefresh");
//                    if (groupListActivity != null) {
//                        groupListActivity.refresh();
//                    }

                    android.app.ActivityManager am = (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
                    List<android.app.ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
                    if (list != null && list.size() > 0) {
                        ComponentName cpn = list.get(0).topActivity;
                        ivNotice.setImageResource(R.mipmap.home_message_r);
                    }

                }
            });
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
        }
    };
}
